#include <stdlib.h>
#include <video-graphics.h>

#include "level.h"
#include "window.h"
#include "xpm.h"
#include "bg.h"
#include "physics.h"
#include "game.h"

/** Imagem da nuvem */
static XPM cloud;

/** Imagem da parede */
static XPM wall;

static Window bg_win = NULL;

/** Número de nuvens */
#define NUM_CLOUDS 10

/** Físicas das nuvens */
static Physics cloud_phys [NUM_CLOUDS];

/** Faz o update do fundo */
static void bg_update_cb (Window win, void *data)
{
	int i;
	int x, y;
	for (i = 0; i < NUM_CLOUDS; i++) {
		physics_cloud (cloud_phys + i, &x, &y);
	}
}

/** Exibe o fundo do menu */
static void menu_draw_cb (Window win, int x, int y, int w, int h, void *data)
{
	if (GAME_SHOW_CREDITS)
		xpm_draw_notrans (win, xpm_get (XPM_CREDITS), 0, 0);
	else
		xpm_draw_notrans (win, xpm_get (XPM_MENU), 0, 0);
}


/** Desenha o fundo */
static void bg_draw_cb (Window win, int x, int y, int w, int h, void *data)
{
	window_fill (win, 1);
	int i, j;
	const char *eis[3] = {"ei06009", "ei07041", "ei09137"};

	for (i = 0; i < NUM_CLOUDS; i++) {
		xpm_draw (win, cloud, x + cloud_phys [i].x, y + cloud_phys [i].y);

		if (GAME_SHOW_CREDITS) {
			window_draw_string (win,
					    eis[((int) cloud_phys [i].y) % 3],
					    x + cloud_phys [i].x + 10,
					    y + cloud_phys [i].y + 10,
					    1);
		}
	}

	LevelCell **map;
	int mapw, maph;

	if (!level_get (&map, &mapw, &maph)) return;

	for (i = x / xpm_level_cell_width; i <= (x+w) / xpm_level_cell_width + 1 && i < mapw; i++) {
		for (j = y / xpm_level_cell_height; j <= (y+h) / xpm_level_cell_height + 1 && j < maph; j++) {
			if (map[j][i] == LEVEL_BLOCK) {
				xpm_draw_notrans (win,
						  wall,
						  i * xpm_level_cell_width,
						  j * xpm_level_cell_height);
			}
		}
	}
}

void bg_create (void)
{
	int mapw, maph;

	if (!level_get (NULL, &mapw, &maph)) {
		// Mostra só o fundo do menu
		bg_win = window_new (0, 0, HRES, VRES, NULL);
		window_set_plane (bg_win, PLANE_BACKGROUND);
		window_show (bg_win, menu_draw_cb);
		return;
	} 

	wall = xpm_get (XPM_WALL);
	cloud = xpm_get (XPM_CLOUD);
	int i;

	// Inicializa a física das núvens
	for (i = 0; i < NUM_CLOUDS; i++) {
		physics_init (cloud_phys + i,
				PHYS_CLOUD,
				rand() % (2 * HRES),
				rand() % (VRES / 3),
				cloud->width,
				cloud->height);
	}

	bg_win = window_new (0, 0, mapw *  xpm_level_cell_width, maph * xpm_level_cell_height, NULL);
	window_set_plane (bg_win, PLANE_BACKGROUND);
	window_show (bg_win, bg_draw_cb);
	window_update (bg_win, bg_update_cb);

}

void bg_destroy (void)
{
	if (bg_win != NULL) {
		window_delete (bg_win);
		bg_win = NULL;
	}
}

